package tech.niua.auth.controller;


import java.util.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tech.niua.auth.domain.SysDept;
import tech.niua.auth.domain.SysResource;
import tech.niua.auth.domain.TreeSelect;
import tech.niua.auth.service.IDeptService;
import tech.niua.auth.service.ISysUserService;
import tech.niua.common.constant.Constants;
import tech.niua.common.model.ResultCode;
import tech.niua.common.model.ResultJson;
import tech.niua.common.utils.StringUtils;
import tech.niua.core.annotation.Log;
import tech.niua.core.enums.BusinessType;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@Api(value = "部门管理")
@RequestMapping("/dept")
public class DeptController {

    private static final Logger logger = LoggerFactory.getLogger(ResourceController.class);

    @Autowired
    private IDeptService deptService;
    @Autowired
    private ISysUserService userService;

    /**
     * 获取部门列表
     */
    @Log(value = "列表查询", businessType = BusinessType.LIST)
    @PreAuthorize("hasAuthority('/dept')")
    @PostMapping("/list")
    public ResultJson list(@RequestBody SysDept dept)

    {

        List<SysDept> depts = deptService.selectDeptList(dept);
        return ResultJson.ok(depts);
    }



    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("hasAuthority('/dept')")
    @GetMapping("/exclude/{deptId}")
    public ResultJson excludeChild(@PathVariable(value = "deptId", required = false) Long deptId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext())
        {
            SysDept d = (SysDept) it.next();
            if (d.getId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""))
            {
                it.remove();
            }
        }
        return ResultJson.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("hasAuthority('/dept')")
    @GetMapping(value = "findById/{deptId}")
    public ResultJson getInfo(@PathVariable Long deptId)
    {
        return ResultJson.ok(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeSelect")
    public ResultJson treeSelect(SysDept dept)
    {

        dept.setDeptStatus("0");
        List<SysDept> depts = deptService.selectDeptList(dept);
        List<TreeSelect> selects = deptService.buildDeptTreeSelect(depts);
        return ResultJson.ok(selects);
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeSelect/{roleId}")
    public ResultJson roleDeptTreeSelect(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        ResultJson r = ResultJson.ok();
        Map<String,Object> map = new HashMap<>();
        map.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        map.put("depts", deptService.buildDeptTreeSelect(depts));
        r.setData(map);
        return r;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("hasAuthority('/dept/saveOrUpdate')")
    @Log(value = "添加操作", businessType = BusinessType.INSERT)
    @PostMapping("/save")
    public ResultJson add(@Validated @RequestBody SysDept dept)
    {
        if (Constants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return ResultJson.failure(ResultCode.SAME_DEPT);
        }
        return ResultJson.ok(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("hasAuthority('/dept/saveOrUpdate')")
    @Log(value = "修改操作", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public ResultJson edit(@Validated @RequestBody SysDept dept)
    {
//        部门名称唯一
        if (Constants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept)))
        {
            return ResultJson.failure(ResultCode.SAME_UPDATE_DEPT);
        }
//        部门的父级部门不能是自己
        else if (dept.getParentId().equals(dept.getId()))
        {
            return ResultJson.failure(ResultCode.UP_NOT_SELF_DEPT);
        }
//        部门停用下面不能有子部门,部门下面也不能有正在使用的用户
        else if (StringUtils.equals(Constants.DEPT_DISABLE, dept.getDeptStatus())
                && deptService.selectNormalChildrenDeptById(dept.getId()) > 0
        )
        {
            return ResultJson.failure(ResultCode.DOWN_NOT_USE_DEPT);
        }
//      部门下面有正在使用的用户，不能停用
        else if (StringUtils.equals(Constants.DEPT_DISABLE, dept.getDeptStatus())
                && userService.selectByDeptId(dept.getId()) > 0
        ){
            return ResultJson.failure(ResultCode.DOWN_HAS_USER_DEPT);
        }
        return ResultJson.ok(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("hasAuthority('/dept/delete')")
    @Log(value = "删除", businessType = BusinessType.DELETE)
    @GetMapping("/delete")
    public ResultJson remove(@RequestParam("deptId") Long deptId)
    {
        if (deptService.hasChildByDeptId(deptId))
        {
            return ResultJson.failure(ResultCode.DOWN_NOT_USE_DEPT);
        }
        if (deptService.checkDeptExistUser(deptId))
        {
            return ResultJson.failure(ResultCode.DOWN_HAS_USER_DEPT);
        }
        return ResultJson.ok(deptService.deleteDeptById(deptId));
    }
}

